package com.runrunfast.fxj.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.runrunfast.fxj.form.PageForm;
import com.runrunfast.fxj.vo.PageVo;
import com.runrunfast.fxj.vo.ResultVo;
import com.runrunfast.fxj.vo.SysUserAddVo;
import com.runrunfast.fxj.vo.SysUserVo;
import com.runrunfast.fxj.entity.SysRole;
import com.runrunfast.fxj.entity.SysUser;
import com.runrunfast.fxj.enums.RoleStatusEnum;
import com.runrunfast.fxj.enums.UserStatusEnum;
import com.runrunfast.fxj.exception.FxjException;
import com.runrunfast.fxj.service.ISysRoleService;
import com.runrunfast.fxj.service.ISysUserService;
import com.runrunfast.fxj.utils.ResultVOUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author 陈胤训
 * @since 2019-03-12
 */

@Slf4j
@Api(value = "后台用户接口",tags = {"后台用户接口"})
@RestController
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;



    @ApiResponses({
            @ApiResponse(code=400,message="请求参数没填好"),
            @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对"),
            @ApiResponse(code = 200, message = "成功返回的records", response = SysUser.class)
    })
    @ApiOperation("用户列表,可实现模糊搜索")
    @GetMapping("/list")
    public ResultVo list(@Validated  PageForm pageVo,BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            log.error("【用户列表】参数不正确, orderForm={}", pageVo);
            log.error(bindingResult.getFieldError().getDefaultMessage());
            throw new FxjException(5,bindingResult.getFieldError().getDefaultMessage());
        }
        PageVo<SysUserVo> pageUserList1 = userService.getPageUserList(pageVo, pageVo.getUsername());

        return ResultVOUtil.success(pageUserList1);
    }

    @ApiOperation("用户添加")
    @PostMapping("/add")
    public ResultVo add(@ApiParam(name="user",value="用户对象",required=true) @Validated SysUserAddVo user
            , BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            log.error("【用户添加】参数不正确, orderForm={}", user);
            log.error(bindingResult.getFieldError().getDefaultMessage());
            throw new FxjException(5,bindingResult.getFieldError().getDefaultMessage());
        }
        if (StringUtils.isEmpty(user)){
            throw new FxjException(UserStatusEnum.OBJECT_NULL.getCode(),UserStatusEnum.OBJECT_NULL.getDesc());
        }
        Integer count = userService.count(new QueryWrapper<SysUser>().eq("phone", user.getPhone()));
        if (count>0){
            throw new FxjException(UserStatusEnum.PHONE_EXIST.getCode(),UserStatusEnum.PHONE_EXIST.getDesc());
        }
        Integer sysRoleId = roleService.getById(user.getSysRoleId()).getSysRoleId();
        if (StringUtils.isEmpty(sysRoleId)){
            throw new FxjException(RoleStatusEnum.ROLE_NULL.getCode(),RoleStatusEnum.ROLE_NULL.getDesc());
        }
        if(!userService.add(user)){
            throw new FxjException(UserStatusEnum.USER_FAILED.getCode(),UserStatusEnum.USER_FAILED.getDesc());
        }
        return ResultVOUtil.success();
    }

    @ApiOperation("用户添加界面")
    @GetMapping("/addPage")
    public ResultVo addPage(){

        List<SysRole> list = roleService.list(new QueryWrapper<SysRole>().eq("status","0"));
        if (list.size() <= 0){
            throw new FxjException(RoleStatusEnum.ROLE_NULL.getCode(),RoleStatusEnum.ROLE_NULL.getDesc());
        }

        return ResultVOUtil.success(list);
    }

    @ApiOperation("修改用户信息")
    @PostMapping("/update")
    public ResultVo update(SysUserVo userVO){
        if (userService.updateInfo(userVO)){
            throw new FxjException(UserStatusEnum.USER_NULL.getCode(),UserStatusEnum.USER_NULL.getDesc());
        }
        return ResultVOUtil.success();
    }

    @ApiOperation("用户修改界面")
    @GetMapping("/updatePage")
    public ResultVo updatePage(@RequestParam("userId") Integer userId){
        SysUser byId = userService.getById(userId);
        if (StringUtils.isEmpty(byId)){
            throw new FxjException(UserStatusEnum.USER_NULL.getCode(),UserStatusEnum.USER_NULL.getDesc());
        }
        return ResultVOUtil.success(byId);
    }

    @ApiOperation("修改用户密码")
    @PostMapping("/updatePassword")
    public ResultVo updatePassword(@RequestParam("userId") Integer userId , @RequestParam("formerPassword") String formerPassword
            , @RequestParam("newPassword") String newPassword ){
        int count = userService.count(new QueryWrapper<SysUser>().eq("sys_user_id", userId).eq("password", formerPassword));
        if (count<= 0 ){
            throw new FxjException(UserStatusEnum.PASSWORD_FAILED.getCode(),UserStatusEnum.PASSWORD_FAILED.getDesc());
        }
        userService.update(new UpdateWrapper<SysUser>().set("password", newPassword).eq("sys_user_id", userId));
        return ResultVOUtil.success();
    }


    @ApiOperation("余额充值")
    @PostMapping("/topUpBalance")
    public ResultVo topUpBalance(@RequestParam("userId") Integer userId , @RequestParam("Balance") BigDecimal balance){
        SysUser byId = userService.getById(userId);
        if (StringUtils.isEmpty(byId)){
            throw new FxjException(UserStatusEnum.USER_NULL.getCode(),UserStatusEnum.USER_NULL.getDesc());
        }
        BigDecimal residueBalance = byId.getBalance();
        userService.update(new UpdateWrapper<SysUser>().set("balance", residueBalance.add(balance)).eq("sys_user_id", userId));
        return ResultVOUtil.success();
    }



}
